import React from 'react';
import { Input, Select, Form, Checkbox, DatePicker, Cascader, Button, Radio, TreeSelect, Drawer, Col, InputNumber, Switch, Table , Upload ,message , Icon} from 'antd';
import * as Utils from '../../utils_yyr/action';
import {baseUrl} from '../../config';

// drawer 新增修改抽屉 type：控件的类型 label:标签名  list:下拉框的值 name：下拉框显示的字段 field:Form表单的key 对应查询接口的参数名
// valueField:下拉框取值的字段 required:代表是否必填 col: 单个控件显示的长度 默认为6  showTime:日期控件是否显示时分秒
// initialValue:初始化表单的值 日期范围控件命名方式: frame_开始时间参数_结束时间参数  单个日期控件命名方式 :date_sendDate
// import config from "../../config";

const { TextArea } = Input;
const { RangePicker, MonthPicker } = DatePicker;
const { TreeNode} = TreeSelect;
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const CheckboxGroup = Checkbox.Group;

class BasicModal extends React.Component {
	state = {
		showIcon: true,
		fileList: [],
		cityList: [],
		fileId:''
	};

	componentDidMount() {
		this.props.onRef(this);
	}

	reset = () => {
		const p = this;
		p.props.form.resetFields();
	};

	handleAdd = () => {
		const p = this;
		p.props.handleOpenModal('add');
	};

	pitchDelete = () => {
		const p = this;
		p.props.pitchDelete();
	};

	onChange = () => { };

	onTreeChange = () => { };

	getFileId = () => { 
		const p = this
		p.props.getFileId()
	}
	
	renderTreeNodes = (data, name, valueField) =>
	// console.log(data, name, valueField)
		data && data.map(item => {
			if (item.children) {
				return (
					<TreeNode title={item[name]} key={item[valueField]} value={item[valueField]} dataRef={item}>
						{this.renderTreeNodes(item.children, name, valueField)}
					</TreeNode>
				);
			}
			return <TreeNode key={item[valueField]} value={item[valueField]} title={item[name]} {...item} />;
		});

	initFormList = () => {
		const p = this;
		const { getFieldDecorator } = p.props.form;
		const { drawerFormList, detail } = this.props;

		const formItemList = [];
		if (drawerFormList && drawerFormList.length > 0) {
			drawerFormList.forEach(item => {
				const { label } = item;
				const { field } = item;
				const { tree } = item;
				const { rules } = item;
				const { dom } = item;
				const { required, parent } = item;
				const rulesType = required ? [{ required: true, message: `${label}必填` }] : false;
				const initialValue = item.initialValue || undefined;
				const frame = [];
				let showAdd = false;
				// if(initialValue&&initialValue instanceof Array){
				//     if(initialValue.length===1&&this.state.fileList&&this.state.fileList.length===0&&!this.state.showIcon)showAdd=true
				//     if(initialValue.length===0&&this.state.fileList&&this.state.fileList.length===0)showAdd=true
				// }

				//时间范围选择器
				if (initialValue && initialValue instanceof Array) {
					initialValue.map(item => {
						frame.push(Utils.getDateByString(item));
					});
				}

				const { placeholder } = item;

				const { style } = item;
				const { name, valueField, showTime } = item;
				const { disabled } = item;
				const formItemLayout = {
					labelAlign: 'left',
					labelCol: {
						xs: { span: 24 },
						sm: { span: 6 }
					},
					wrapperCol: {
						xs: { span: 24 },
						sm: { span: 16 }
					}
				};
				const p=this;
				const props = {
					name: 'file',
					action:baseUrl+item.apiPath,
					headers: {
					Token: localStorage.getItem('token'),
				},
				data:item.parameter?item.parameter:{},
					multiple:true,
					onChange(info) {
						if (info.file.status !== 'uploading') {
						}
						if (info.file.status === 'done') {
							message.success(`${info.file.name} 上传成功.`);
						if(item.load){
							// item.fetch();
						}
						if(item.fileId){
							console.log(info.file.response.data.id)
							p.setState({fileId:info.file.response.data.id})
							// item.getFileId(info.file.response.data.id);
						}
						} else if (info.file.status === 'error') {
							message.error(`${info.file.name} 上传失败.`);
						}
					},
				};
				if (item.type === 'TITLE') {
					const timeFrame = (
						<Col span={24}>
							<h3 style={{ fontWeight: 'bold', marginBottom: '10px' }}>{ label }</h3>
						</Col>

					);
					formItemList.push(timeFrame);
				} else if (item.type === 'TIMEFRAME') {
					const timeFrame = (
						<Col span={12} style={{ paddingLeft: '15px' }}>
							<FormItem label={label} key={field} {...formItemLayout}>
								{getFieldDecorator(`${field}`, {
									initialValue: frame
								})(<RangePicker style={{ width: '100%' }} showTime={showTime ? true : false} placeholder="起始日期" format={showTime ? 'YYYY-MM-DD HH:mm:ss' : 'YYYY-MM-DD'} />)}
								{dom}
							</FormItem>
						</Col>

					);
					formItemList.push(timeFrame);
				} else if (item.type === 'DATE') {
					const date = (
						<Col span={12} style={{ paddingLeft: '15px' }}>
							<FormItem label={label} key={field} {...formItemLayout}>
								{getFieldDecorator(`${field}`, {
									rules: rulesType,
									initialValue: Utils.getDateByString(initialValue)
								})(<DatePicker style={{ width: '100%' }} showTime={showTime ? true : false} format={showTime ? 'YYYY-MM-DD HH:mm:ss' : 'YYYY-MM-DD'}  placeholder={placeholder ? placeholder:`请输入${label}`} />)}
							</FormItem>
						</Col>

					);
					formItemList.push(date);
				} else if (item.type === 'INPUT') {
					const INPUT = (
						<Col span={12} style={{ paddingLeft: '15px' }}>
							<FormItem label={label} key={field} {...formItemLayout}>
								{getFieldDecorator(`${field}`, {
									rules: rulesType,
									initialValue
								})(<Input type="text" placeholder={placeholder ? placeholder:`请输入${label}`} />)}
								{dom}
							</FormItem>
						</Col>

					);
					formItemList.push(INPUT);
				} else if (item.type === 'INPUTNUMBER') {
					const inputNumber = (
						<Col span={12} style={{ paddingLeft: '15px' }}>
							<FormItem label={label} key={field} {...formItemLayout}>
								{getFieldDecorator(`${field}`, {
									rules: rulesType,
									initialValue
								})(<InputNumber style={{ width: '100%' }}  placeholder={placeholder ? placeholder:`请输入${label}`} />)}
							</FormItem>
						</Col>

					);
					formItemList.push(inputNumber);
				} else if (item.type === 'SWITCH') {
					const switch1 = (
						<Col span={12} style={{ paddingLeft: '15px' }}>
							<FormItem label={label} key={field} {...formItemLayout}>
								{getFieldDecorator(`${field}`, {
									rules: rulesType,
									initialValue,
									valuePropName: 'checked'
								})(<Switch />)}
							</FormItem>
						</Col>

					);
					formItemList.push(switch1);
				} else if (item.type === 'NUMBERFRAME') {
					let arr = field.split('_');
					const number = (
						<Col span={12} style={{ paddingLeft: '15px' }}>
							<Col span={24}>
								<Col span={12}>
									<FormItem label={label} key={field}>
										{getFieldDecorator(`${arr[1]}`)(<InputNumber style={{ width: '100%' }} placeholder="最高数量" />)}
									</FormItem>
								</Col>
								<Col span={12}>
									<FormItem key={field}>{getFieldDecorator(`${arr[2]}`)(<InputNumber style={{ width: '100%' }} placeholder="最低数量" max={p.props.form.getFieldValue(arr[1]) ? p.props.form.getFieldValue(arr[1]) : Infinity} />)}</FormItem>
								</Col>
							</Col>
						</Col>

					);
					formItemList.push(number);
				} else if (item.type === 'MONTHDATE') {
					const month = (
						<Col span={12} style={{ paddingLeft: '15px' }}>
							<FormItem label={label} key={field} style={style} {...formItemLayout}>
								{getFieldDecorator(`${field}`, {
									rules: rulesType,
									initialValue
								})(<MonthPicker placeholder={`请选择${label}`} style={{ width: '100%' }} showTime={showTime ? true : false} />)}
							</FormItem>
						</Col>

					);
					formItemList.push(month);
				} else if (item.type === 'TEXTAREA') {
					const TEXTAREA = (
						<Col span={24} style={{ paddingLeft: '15px' }}>
							<FormItem label={label} key={field} style={style} {...formItemLayout}>
								{getFieldDecorator(`${field}`, {
									rules: rulesType,
									initialValue
								})(<TextArea autosize={{ minRows: 3 }}  placeholder={placeholder ? placeholder:`请输入${label}`} />)}
								{dom}
							</FormItem>
						</Col>

					);
					formItemList.push(TEXTAREA);
				} else if (item.type === 'SELECT') {
					const SELECT = (
						<Col span={12} style={{ paddingLeft: '15px' }}>
							<FormItem label={label} key={field} {...formItemLayout}>
								{getFieldDecorator(`${field}`, {
									initialValue, // true | false
									rules: rulesType
								})(
									<Select  placeholder={placeholder ? placeholder:`请选择${label}`}  onChange={parent ? value => p.props.parentChange(value) : ''} showSearch allowClear filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}>
										{Utils.getOptionList(item.list, name, valueField)}
									</Select>
								)}
							</FormItem>
						</Col>

					);
					formItemList.push(SELECT);
				} else if (item.type === 'TREESELECT') {
					const REDIO = (
						<Col span={12} style={{ paddingLeft: '15px' }}>
							<FormItem label={label} key={field} {...formItemLayout}>
								{getFieldDecorator(`${field}`, {
									rules: rulesType,
									initialValue
								})(<TreeSelect onChange={this.onTreeChange}  placeholder={placeholder ? placeholder:`请选择${label}`}  showCheckedStrategy="SHOW_PARENT" searchPlaceholder={item.list} treeCheckable={item.treeCheckable} searchPlaceholder="Please select" allowClear={item.allowClear}>
									{this.renderTreeNodes(item.list, item.name, item.valueField)}
									</TreeSelect>)}
							</FormItem>
						</Col>

					);
					formItemList.push(REDIO);
				} else if (item.type === 'RADIO') {
					const REDIO = (
						<Col span={12} style={{ paddingLeft: '15px' }}>
							<FormItem label={label} key={field} {...formItemLayout}>
								{getFieldDecorator(`${field}`, {
									rules: rulesType,
									initialValue: initialValue || 0
								})(
									<RadioGroup onChange={this.onChange} >
										{Utils.getRadioList(item.list, name)}
									</RadioGroup>
								)}
							</FormItem>
						</Col>

					);
					formItemList.push(REDIO);
				} else if (item.type === 'CHECKBOX') {
					const CHECKBOX = (
						<Col span={12} style={{ paddingLeft: '15px' }}>
							<FormItem label={label} key={field} {...formItemLayout}>
								{getFieldDecorator(`${field}`, {
									rules: rulesType,
									valuePropName: 'checked',
									initialValue // true | false
									
								})(
									<CheckboxGroup>
										{Utils.getCheckboxList(item.list)}
									</CheckboxGroup>
								)}
							</FormItem>
						</Col>

					);
					formItemList.push(CHECKBOX);
				} else if (item.type === 'CASCADER') {
					const CASCADER = (
						<Col span={12} style={{ paddingLeft: '15px' }}>
							<FormItem label={label} key={field} {...formItemLayout}>
								{getFieldDecorator(`${field}`, {
									rules: rulesType,
									initialValue // true | false
								})(<Cascader placeholder={placeholder} allowClear options={tree} expandTrigger="hover" />)}
							</FormItem>
						</Col>

					);
					formItemList.push(CASCADER);
				} else if (item.type === 'TABLE') {
					const columns = [
						{ title: '删除', width: 100, dataIndex: 'operation',
							render: (text, record) => (<span><a onClick={this.handleDetail}>删除</a></span>)
						},
						{ title: '姓名', width: 100, dataIndex: 'xingm' },
						{ title: '维修开始时间', width: 200, dataIndex: 'start' },
						{ title: '维修完成时间', width: 200, dataIndex: 'end' },
						{ title: '维修用时', width: 150, dataIndex: 'usertime' },
						{ title: '实际维修工时', width: 150, dataIndex: 'usetime' },
						{ title: '内容或步骤', width: 200, dataIndex: 'text' }

					]
					const dataSourceDemo = [
						{xingm:'管理员',start:'2021-04-12 00:00',end:'2021-04-13 00:00',usertime:'12小时',usetime:'12小时',text:''}
					]

					const CASCADER = (
						<Col span={24} style={{ paddingLeft: '15px' }}>
							<Table columns={columns} rowKey={(record, index) => index}  size="small" dataSource={dataSourceDemo} pagination={false} scroll={{ x: 1000 }} />
						</Col>
					);
					formItemList.push(CASCADER);
				} else if (item.type === 'BOTTOM') {
					const CASCADER = (
						<Col span={12} style={{ paddingLeft: '15px' }}>
							<Button type="primary" key={field} {...formItemLayout}>{label}
								{/* {getFieldDecorator(`${field}`, {
									initialValue // true | false
								})(<Cascader placeholder={placeholder} allowClear options={tree} expandTrigger="hover" />)} */}
							</Button>
						</Col>
					);
					formItemList.push(CASCADER);
				} else if (item.type === 'FILEUPLOAD') {
					const CASCADER = (
						<Col span={12} style={{ paddingLeft: '15px' }}>
							<FormItem label={label} key={field} {...formItemLayout}>
								{getFieldDecorator(`${field}`, {
									rules: rulesType,
									initialValue // true | false,
								})(<Upload {...props} style={{display:'inline-block'}}><Button type='primary'><Icon type="upload" />{item.buttonName}</Button></Upload>)}
							</FormItem>
							{/* <FileUpload buttonName={item.buttonName} apiPath={item.apiPath} load={item.load} fetch={()=>item.fetch} getFileId={this.getFileId} fileId={true}/> */}
							
						</Col>
					);
					formItemList.push(CASCADER);
				}
			});
		}
		return formItemList;
	};

	closeModal = () => {
		const p = this;
		const { onClose } = p.props;
		// form.resetFields();
		onClose();
	};

	handleSubmit = () => {
		const p = this;
		const { form } = this.props;
		form.validateFieldsAndScroll((err, fieldsValue) => {
			console.log(fieldsValue)
			if (err) {
				return;
			}
			for (var key in fieldsValue) {
				//时间范围选择器
				if (key.indexOf('frame_') === 0) {
					if (fieldsValue[key] && fieldsValue[key].length) {
						let arr = key.split('_');
						fieldsValue[arr[1]] = Utils.getDate(fieldsValue[key][0]);
						fieldsValue[arr[2]] = Utils.getDate(fieldsValue[key][1]);
					}
					delete fieldsValue[key];
				}
				//单个时间选择器
				if (key.indexOf('date_') === 0) {
					if (fieldsValue[key]) {
						let arr = key.split('_');
						fieldsValue[arr[1]] = Utils.getDate(fieldsValue[key]);
					}
					delete fieldsValue[key];
				}
				//单个时间选择器--需要时分秒
				if (key.indexOf('dateSec_') === 0) {
					if (fieldsValue[key]) {
						let arr = key.split('_');
						fieldsValue[arr[1]] = Utils.getDateHHMMYY_HHMMSS(fieldsValue[key]);
					}
					delete fieldsValue[key];
				}

				//月选择器
				if (key.indexOf('month_') === 0) {
					if (fieldsValue[key]) {
						let arr = key.split('_');
						fieldsValue[arr[1]] = Utils.getStringByDate(fieldsValue[key], 'YYYY-MM');
					}
					delete fieldsValue[key];
				}

				//多选框结果字符串拼接
				if (key.indexOf('tostrs_') === 0) {
					if (fieldsValue[key]) {
						let arr = key.split('_');
						let str = ''
						for(var items of fieldsValue[key]){
							str += items + ','
						}
						fieldsValue[arr[1]] = str.slice(0, str.length - 1) ;
						console.log(str)
					}
					delete fieldsValue[key];
				}

				//上传文件fileid记录
				console.log(key.indexOf('upload_'))
				if (key.indexOf('upload_') === 0) {
					// if (this.state.fileId) {
					let arr = key.split('_');
					fieldsValue[arr[1]] = this.state.fileId ;
					// }
					delete fieldsValue[key];
				}
			}
			p.props.submit(fieldsValue);
		});
	};

	render() {
		const p = this;
		const { visible, title, detail, width } = this.props;
		const modalProps = {
			title,
			visible,
			width,
			onClose() {
				p.closeModal();
			}
		};

		return (
			<Drawer {...modalProps}>
				<Form layout="horizontal">{p.initFormList()}</Form>
				<div style={{ position: 'absolute', right: 0, bottom: 0, width: '100%', borderTop: '1px solid #e9e9e9', padding: '10px 16px', background: '#fff', textAlign: 'right' }}>
					<Button type="primary" onClick={this.handleSubmit} style={{ marginRight: 8 }}>
						保存
					</Button>
					<Button onClick={() => p.closeModal()} style={{ marginRight: 8 }}>
						关闭
					</Button>
				</div>
			</Drawer>
		);
	}
}
export default Form.create({})(BasicModal);
